<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"blog.upup.fun","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="拖拽排序的简单优化方案，顺便记录下一些RN通用的优化思路。">
<meta property="og:type" content="article">
<meta property="og:title" content="【干货】React Native性能优化——长列表拖拽排序">
<meta property="og:url" content="http://blog.upup.fun/2023/01/09/ReactNative%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E2%80%94%E2%80%94%E6%8B%96%E6%8B%BD%E6%8E%92%E5%BA%8F/index.html">
<meta property="og:site_name" content="猫头猫">
<meta property="og:description" content="拖拽排序的简单优化方案，顺便记录下一些RN通用的优化思路。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://storage.upup.fun/musicfree/K4BF_4TJA%7D1%7DISIGJ%5B%7DWEAT.png">
<meta property="og:image" content="http://storage.upup.fun/musicfree/%29OM6%604OYJ%7BVK%7DP%29%28W%24IFZLC.png">
<meta property="og:image" content="http://storage.upup.fun/musicfree/G%7D%24VCM1F0I2W%28NGH%60_D%7B%28%40N.png">
<meta property="og:image" content="http://storage.upup.fun/musicfree/iPhone%2014_13%20Pro.png">
<meta property="og:image" content="http://storage.upup.fun/musicfree/QQ%E5%9B%BE%E7%89%8720230110234021.png">
<meta property="article:published_time" content="2023-01-09T12:24:18.000Z">
<meta property="article:modified_time" content="2023-01-10T17:21:25.768Z">
<meta property="article:author" content="猫头猫">
<meta property="article:tag" content="React Native">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://storage.upup.fun/musicfree/K4BF_4TJA%7D1%7DISIGJ%5B%7DWEAT.png">

<link rel="canonical" href="http://blog.upup.fun/2023/01/09/ReactNative%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E2%80%94%E2%80%94%E6%8B%96%E6%8B%BD%E6%8E%92%E5%BA%8F/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【干货】React Native性能优化——长列表拖拽排序 | 猫头猫</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">猫头猫</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-works">

    <a href="/works/" rel="section"><i class="fa fa-smile fa-fw"></i>小作品</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.upup.fun/2023/01/09/ReactNative%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E2%80%94%E2%80%94%E6%8B%96%E6%8B%BD%E6%8E%92%E5%BA%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="猫头猫">
      <meta itemprop="description" content="如果我是一只小猫咪，每天只要喵喵叫。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="猫头猫">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【干货】React Native性能优化——长列表拖拽排序
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2023-01-09 20:24:18" itemprop="dateCreated datePublished" datetime="2023-01-09T20:24:18+08:00">2023-01-09</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%89%8D%E7%AB%AF/%E7%A7%BB%E5%8A%A8%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">移动端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>10k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>9 分钟</span>
            </span>
            <div class="post-description">拖拽排序的简单优化方案，顺便记录下一些RN通用的优化思路。</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>这是在做业余项目<a target="_blank" rel="noopener" href="https://github.com/maotoumao/MusicFree">MusicFree</a>时的一些技术探索，简单记录一下优化过程和思考方式。前情可以戳<a href="http://blog.upup.fun/2022/10/04/%E5%86%99%E4%B8%80%E4%B8%AA%E5%85%A8%E7%BD%91%E6%9C%80%E5%85%A8%E7%9A%84%E9%9F%B3%E4%B9%90%E6%92%AD%E6%94%BE%E5%99%A8/">这篇文章</a>。</p>
<p>先来看最终的效果，再来说需求和实现：</p>
<video src="http://storage.upup.fun/musicfree/313DA58C945D3DD5A4F005C0A6CDD29F.mp4" controls ></video>

<p>在上述视频中可以看到，这是一个由628首歌曲构成的歌单<strong>长列表</strong>，主要功能是对歌单里面的歌曲进行<strong>拖拽排序</strong>和<strong>批量选择操作</strong>，看起来还是比较流畅的。</p>
<h1 id="需求分析-amp-实现思路"><a href="#需求分析-amp-实现思路" class="headerlink" title="需求分析&amp;实现思路"></a>需求分析&amp;实现思路</h1><p>首先来明确一下需求，或者说最终要达到的目标吧。其实在前言部分已经够明确了，关键词就是<strong>长列表</strong>、<strong>拖拽排序</strong>和<strong>批量选择</strong>；作为一个业余项目，最终要达到的目标也掺杂着强烈的个人偏好：<strong>不卡、实用</strong>。</p>
<h2 id="方案1：做一个调包侠"><a href="#方案1：做一个调包侠" class="headerlink" title="方案1：做一个调包侠"></a>方案1：做一个调包侠</h2><p>为了实现以上效果，第一反应就是寻找社区开源项目，看有没有类似的库。网上搜了一圈，还在维护的貌似就只有这个<a target="_blank" rel="noopener" href="https://github.com/computerjazz/react-native-draggable-flatlist">react-native-draggable-flatlist</a>库了。</p>
<p>抱着试试看的心态，我们把<a target="_blank" rel="noopener" href="https://github.com/maotoumao/MusicFree/blob/draggable-flatlist/src/pages/musicListEditor/components/musicList.tsx">代码写好</a>：</p>
<blockquote>
<p>其实最早期简单试用了一下，就把这个方案否决掉了。原因也很简单，一方面是有点卡，另一方面是它不知道为啥会导致模拟器debug时崩溃。下面的对比实验视频是在最后确定方案之后做的，忽略交互方式和一些底色之类的，相关的优化都是相同的。</p>
</blockquote>
<video src="http://storage.upup.fun/musicfree/SVID_20230109_230717_1.mp4" controls></video>

<p>可以发现其中有几点体验较差的地方：</p>
<ol>
<li>拖拽到顶自动滑动的时候，选中的元素好像一直在抖</li>
<li>单选时选中状态反应较快（和最终版速度差不多，因为这里的优化一样）；但<strong>全选、全不选有明显延迟</strong>(~1s)</li>
<li>拖拽结束后，<strong>花费大量时间执行回调函数</strong>（可以观察一下颜色，停止拖拽后选中的元素还会保持很长一段时间的选中态）</li>
</ol>
<p>回顾下目标：</p>
<ul>
<li>卡吗？卡。</li>
<li>实用吗？凑合能用。</li>
<li>满意吗？凑合能用可以，卡的这么明显忍不了。</li>
<li>那怎么办？自己写个吧。</li>
</ul>
<h2 id="方案2：自己实现"><a href="#方案2：自己实现" class="headerlink" title="方案2：自己实现"></a>方案2：自己实现</h2><h3 id="通用？定制？"><a href="#通用？定制？" class="headerlink" title="通用？定制？"></a>通用？定制？</h3><p>既然要自己实现，那么还是得好好设计一下。第一个要思考的问题便是：要做一个通用方案还是做一个定制的方案。因为这可能会涉及到方案设计，如果要做一个通用方案，那可能会更少的trick，更多的配置来满足通用性和灵活性。如果是一个仅仅在当前项目中使用的方案，那就可以加很多<strong>前提条件</strong>和<strong>折中技巧</strong>了。<br>仔细想了想，首先我在短期内不太会用React Native开一个新的有长列表的坑，其次我也不见得做的会比react-native-draggable-flatlist更好，也不必顾此失彼，先用个项目中的定制方案满足自己的需求就足够了。</p>
<h3 id="怎么才能不卡？"><a href="#怎么才能不卡？" class="headerlink" title="怎么才能不卡？"></a>怎么才能不卡？</h3><p>第二个要思考的问题理所当然是如何实现目标了。那么自然有个问题：为啥会卡？<br>想一想我们用的库是什么：react-native-draggable-<strong>flatlist</strong>。对，flatlist。简单来说，Flatlist在每次滚动时会<strong>批量预渲染</strong>一定区域内的元素，并把区域外的元素<strong>销毁</strong>。我们来看一下这张图就明白了：</p>
<p><img src="http://storage.upup.fun/musicfree/K4BF_4TJA%7D1%7DISIGJ%5B%7DWEAT.png" alt="flatlist"></p>
<p>可以看出，始终会保持<strong>120个元素</strong>在内存中，每次滑动时会<strong>销毁</strong>不在区域中的元素。Shopify团队针对这一点进行优化开发了<a target="_blank" rel="noopener" href="https://shopify.github.io/flash-list/">Flashlist</a>，它的原理大概是首先渲染一定量的初始元素；但在滑动时滑出视窗的元素不会销毁，而是重复利用：</p>
<p><img src="http://storage.upup.fun/musicfree/%29OM6%604OYJ%7BVK%7DP%29%28W%24IFZLC.png" alt="flashlist"></p>
<p>同时，由于其一次渲染到屏幕上的元素较少（20个之于120个），当<strong>全选</strong>时需要重新渲染的元素数目也会大大减少（简单算一下，少渲染5/6的内容）。它们官网上说相对于原生的Flatlist性能有5~10倍的提升，既然这样，那就用Flashlist好了。</p>
<p><img src="http://storage.upup.fun/musicfree/G%7D%24VCM1F0I2W%28NGH%60_D%7B%28%40N.png" alt="官网"></p>
<h3 id="拖拽排序怎么实现？"><a href="#拖拽排序怎么实现？" class="headerlink" title="拖拽排序怎么实现？"></a>拖拽排序怎么实现？</h3><h4 id="再来一个问题"><a href="#再来一个问题" class="headerlink" title="再来一个问题"></a>再来一个问题</h4><p>以上两个问题思考完了：为了达成目标，我们可以随意在实现时加一些前提/trick，并且我们要把flatlist切换成flashlist以提升长列表性能。接下来就是比较麻烦的地方了：<strong>如何实现拖拽排序</strong>。都思考了这么多问题了，不妨再多加一个问题：最终要实现的效果是<strong>侧重UI交互</strong>还是<strong>侧重功能</strong>？</p>
<p>如果侧重交互的话，可以大概设计一下理想的效果：</p>
<ol>
<li>在按住某一个元素上下拖动时，它需要出现在它正确的位置;</li>
<li>并且它的兄弟元素都会被顺滑的挤到一边；</li>
<li>滑动的位置越靠两端，滑动速度越快；</li>
<li>在放手的一瞬间，它会立刻出现在它被移动到位置上。</li>
</ol>
<p>从实现角度来说：</p>
<ol>
<li>在选中一个元素的一瞬间，它的zIndex会被重新设置;</li>
<li>随着手指的拖动，它和它的兄弟元素的y轴位置都会通过setNativeProps调整；</li>
<li>同时需要记录下手指位置距离列表两端的距离来决定是否需要继续scroll，以及下一个scroll的位置；</li>
<li>在放手的一瞬间，这些元素的位置和y轴位置（因为通过setNativeProps改过了）会被重新计算。</li>
</ol>
<p>确实，想的挺好，但Flatlist（Flashlist的参数和原生flatlist类似）连scroll的速度都难控制，更别说这些特殊的效果了。再想想目标，交互可以砍一些，果断<strong>侧重功能</strong>。</p>
<h4 id="前提条件"><a href="#前提条件" class="headerlink" title="前提条件"></a>前提条件</h4><p>啰嗦了这么多，其实都是为了给最终实现减少难度。现在我们可以比较放肆的给拖拽排序列表加前提条件了：</p>
<ul>
<li><p>列表距离顶部和底部的距离已知</p>
<blockquote>
<p>反正是个个人项目，那我有理由要求整个APP中所有的拖拽列表样式保持一致。这也就意味着列表高度可以直接简单算出来。</p>
</blockquote>
</li>
<li><p>列表里面的元素高度、布局稳定，不会随着状态的变化有较大变化</p>
<blockquote>
<p>这样即便有需要传进来的样式，可以用ref存下样式；参数变化导致重新渲染时不需要重新创建样式对象；同时很多布局信息，如当前位置等也可以简单的算出来。</p>
</blockquote>
</li>
<li><p>交互方式固定，每个元素的右边有个小按钮，只能靠这个按钮进行拖拽</p>
<blockquote>
<p>统一交互的话，这样控制拖拽的逻辑可以直接做在列表组件内部了。具体一点说，通过列表传入的renderItem参数渲染的组件仅仅是下图中的红色部分；蓝色区域用来控制拖拽；拖拽的逻辑和样式仅仅由列表组件内部控制：</p>
</blockquote>
</li>
</ul>
<blockquote>
<p><img src="http://storage.upup.fun/musicfree/iPhone%2014_13%20Pro.png" alt=""></p>
</blockquote>
<ul>
<li>目标元素拖动时，它的兄弟元素位置不会出现变化；目标元素拖到哪个元素的上方，就代表它最终会被移动到哪个位置<blockquote>
<p>这样只需要通过setNativeProps改变一个元素的属性，甚至可以通过一些trick完全不改动列表元素。</p>
</blockquote>
</li>
</ul>
<p>前提条件加完了，是时候开始设计技术方案了。</p>
<h1 id="技术方案"><a href="#技术方案" class="headerlink" title="技术方案"></a>技术方案</h1><p>把拖拽排序这个问题分解一下，又可以拆成几个子问题：</p>
<ul>
<li>滚动行为</li>
<li>高亮元素</li>
<li>结束回调<br>接下来就尝试从这几个角度去设计一下。</li>
</ul>
<h2 id="滚动行为"><a href="#滚动行为" class="headerlink" title="滚动行为"></a>滚动行为</h2><h3 id="整体结构"><a href="#整体结构" class="headerlink" title="整体结构"></a>整体结构</h3><p>滚动行为还是比较明了的。首先，列表是一个FlashList（删掉了很多无关代码，代码多了不好看），相关的事件以及需要在这些事件内关注的行为如下：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/** */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SortableFlatList</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 不要干扰原始数据</span></span><br><span class="line">    <span class="keyword">const</span> [_data, _setData] = useState([...(data ?? [])]);</span><br><span class="line">    <span class="comment">// 是否禁止滚动</span></span><br><span class="line">    <span class="keyword">const</span> [scrollEnabled, setScrollEnabled] = useState(<span class="literal">true</span>);</span><br><span class="line">    <span class="comment">// 是否处在激活状态, -1表示无，其他表示当前激活的下标</span></span><br><span class="line">    <span class="keyword">const</span> activeRef = useRef(-<span class="number">1</span>);</span><br><span class="line">    <span class="comment">// content偏移值 用来记录滚动距离</span></span><br><span class="line">    <span class="keyword">const</span> contentOffsetYRef = useRef&lt;<span class="built_in">number</span>&gt;(-<span class="number">1</span>);</span><br><span class="line">    <span class="comment">// 目标在屏幕内移动距离</span></span><br><span class="line">    <span class="keyword">const</span> targetOffsetYRef = useRef&lt;<span class="built_in">number</span>&gt;(<span class="number">0</span>);</span><br><span class="line">    <span class="comment">// 当前移动的方向，0表示不移动，1表示向下，-1表示向上</span></span><br><span class="line">    <span class="keyword">const</span> direction = useSharedValue(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">FlashList</span></span></span></span><br><span class="line"><span class="tag"><span class="xml">                <span class="attr">scrollEnabled</span>=<span class="string">&#123;scrollEnabled&#125;</span></span></span></span><br><span class="line"><span class="tag"><span class="xml">                <span class="attr">ref</span>=<span class="string">&#123;_</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="xml">                    // list的引用，需要用它控制滚动</span></span><br><span class="line"><span class="xml">                &#125;&#125;</span></span><br><span class="line"><span class="xml">                onLayout=&#123;evt =&gt; &#123;</span></span><br><span class="line"><span class="xml">                    // 布局信息，需要用它拿到尺寸</span></span><br><span class="line"><span class="xml">                &#125;&#125;</span></span><br><span class="line"><span class="xml">                data=&#123;_data&#125;</span></span><br><span class="line"><span class="xml">                estimatedItemSize=&#123;itemHeight&#125; // 这里其实是每一个元素的高度，直接固定了，也是一个优化项</span></span><br><span class="line"><span class="xml">                scrollEventThrottle=&#123;16&#125; // 滚动事件的节流回调</span></span><br><span class="line"><span class="xml">                onTouchStart=&#123;e =&gt; &#123;</span></span><br><span class="line"><span class="xml">                    if(activeRef.current !== -1) &#123;</span></span><br><span class="line"><span class="xml">                        // 触摸开始时，如果是在拖动状态，那就需要记录下初始位置</span></span><br><span class="line"><span class="xml">                        // 高亮元素</span></span><br><span class="line"><span class="xml">                    &#125;</span></span><br><span class="line"><span class="xml">                &#125;&#125;</span></span><br><span class="line"><span class="xml">                onTouchMove=&#123;e =&gt; &#123;</span></span><br><span class="line"><span class="xml">                    if(activeRef.current !== -1) &#123;</span></span><br><span class="line"><span class="xml">                        // 移动时，如果在拖动状态，需要更新滚动速度，并记录移动的距离</span></span><br><span class="line"><span class="xml">                        // 修改高亮元素位置</span></span><br><span class="line"><span class="xml">                    &#125;</span></span><br><span class="line"><span class="xml">                &#125;&#125;</span></span><br><span class="line"><span class="xml">                onTouchEnd=&#123;e =&gt; &#123;</span></span><br><span class="line"><span class="xml">                    if(activeRef.current !== -1) &#123;</span></span><br><span class="line"><span class="xml">                        // 如果是拖动状态，那就执行最终的回调</span></span><br><span class="line"><span class="xml">                        // 重置样式</span></span><br><span class="line"><span class="xml">                    &#125;</span></span><br><span class="line"><span class="xml">                &#125;&#125;</span></span><br><span class="line"><span class="xml">                onTouchCancel=&#123;() =&gt; &#123;</span></span><br><span class="line"><span class="xml">                    // 取消时所有的符号位和状态</span></span><br><span class="line"><span class="xml">                &#125;&#125;</span></span><br><span class="line"><span class="xml">                onScroll=&#123;e =&gt; &#123;</span></span><br><span class="line"><span class="xml">                    // 在这里记录下y轴的偏移</span></span><br><span class="line"><span class="xml">                    if(activeRef.current !== -1) &#123;</span></span><br><span class="line"><span class="xml">                        // 滚动时，如果在拖动状态</span></span><br><span class="line"><span class="xml">                    &#125;</span></span><br><span class="line"><span class="xml">                &#125;&#125;</span></span><br><span class="line"><span class="xml">                renderItem=&#123;(&#123;item, index&#125;) =&gt; &#123;</span></span><br><span class="line"><span class="xml">                    return (</span></span><br><span class="line"><span class="xml">                        <span class="tag">&lt;<span class="name">SortableFlatListItem</span>/&gt;</span> // 渲染一个满足前提条件的特定元素：它固定右侧是一个用来拖拽的小按钮，高度也是固定的。</span></span><br><span class="line"><span class="xml">                    );</span></span><br><span class="line"><span class="xml">                &#125;&#125;</span></span><br><span class="line"><span class="xml">            /&gt;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">_SortableFlatListItem</span>(<span class="params">props: ISortableFlatListItemProps</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123;</span><br><span class="line">        setScrollEnabled,</span><br><span class="line">        renderItem,</span><br><span class="line">        setActiveItem,</span><br><span class="line">        item,</span><br><span class="line">        index,</span><br><span class="line">        activeRef,</span><br><span class="line">    &#125; = props;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        <span class="xml"><span class="tag">&lt;<span class="name">View</span>&gt;</span></span></span><br><span class="line"><span class="xml">            &#123;renderItem(&#123;item, index&#125;)&#125;</span></span><br><span class="line"><span class="xml">            <span class="tag">&lt;<span class="name">Pressable</span></span></span></span><br><span class="line"><span class="tag"><span class="xml">                <span class="attr">onTouchStart</span>=<span class="string">&#123;()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="xml">                    if (activeRef.current !== -1) &#123;</span></span><br><span class="line"><span class="xml">                        return;</span></span><br><span class="line"><span class="xml">                    &#125;</span></span><br><span class="line"><span class="xml">                    /** 使用ref避免其它组件重新渲染; 由于事件冒泡，这里会先触发 */</span></span><br><span class="line"><span class="xml">                    activeRef.current = index;</span></span><br><span class="line"><span class="xml">                    /** 锁定滚动 */</span></span><br><span class="line"><span class="xml">                    setScrollEnabled(false);</span></span><br><span class="line"><span class="xml">                    setActiveItem(item);</span></span><br><span class="line"><span class="xml">                &#125;&#125;</span></span><br><span class="line"><span class="xml">                style=&#123;styleRef.current.btn&#125;&gt;</span></span><br><span class="line"><span class="xml">                <span class="tag">&lt;<span class="name">Icon</span> <span class="attr">name</span>=<span class="string">&quot;menu&quot;</span>/&gt;</span></span></span><br><span class="line"><span class="xml">            <span class="tag">&lt;/<span class="name">Pressable</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;/<span class="name">View</span>&gt;</span></span></span><br><span class="line">    );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> SortableFlatListItem = memo(</span><br><span class="line">    _SortableFlatListItem,</span><br><span class="line">    <span class="function">(<span class="params">prev, curr</span>) =&gt;</span> prev.index === curr.index &amp;&amp; prev.item === curr.item,</span><br><span class="line">);</span><br></pre></td></tr></table></figure><br>以上代码中SortableFlatList就是暴露给外部模块直接使用的列表，列表内部其实是用SortableFlatListItem，它由两部分构成，左边一半是使用renderItem直接渲染的组件，右边一半是仅可以用来拖拽的一个Icon按钮。  </p>
<p>我们会遇到的第一个问题是<strong>禁用滚动的时机</strong>。当拖拽组件时，整个列表需要禁用滚动（仅可以由列表的ref手动控制滚动），不然的话随着拖拽可能触发了滚动事件，导致拖拽失效。由于禁用/启用滚动一定需要重新渲染列表，因此scrollEnabled是一个state，在_SortableFlatListItem的Icon按钮的触摸事件中设置它为false即可，也就是代码中锁定滚动注释的下面那行。</p>
<p>第二个问题则是，如何记录<strong>当前正在拖拽的元素</strong>，以及这个元素的<strong>初始位置</strong>。根据之前的描述，正在拖拽的元素具有高亮效果，这个高亮效果必然是通过一个<strong>state</strong>控制的；我们可以在SortableFlatListItem中Icon按钮的onPress事件中触发setActiveItem，来更新当前的选中项。而为了得到这个元素的初始位置，我们必须想办法把用户<strong>触碰Icon按钮时的坐标</strong>传递给SortableFlatList。</p>
<p>为了得到这一部分，这里用了一些小小的trick：我们知道React Native的事件也有<strong>冒泡机制</strong>，也就意味着事件会从子组件冒泡到父组件。</p>
<p>具体一些说：子组件SortableFlatListItem中Icon按钮的onTouchStart会先触发，接下来会冒泡到SortableFlat的onTouchStart事件。这就给了我们一些可乘之机：我们可以再使用一个ref记录当前是否处于拖拽态，也就是代码中的activeRef，至于它的值，存放<strong>拖拽中元素的下标</strong>就完全足够了。</p>
<p>如果触发拖拽，那么在Icon按钮的onTouchStart中同时更新activeItem和这个activeRef。接下来，事件会冒泡到SortableFlatList中，这时父组件的onTouchStart捕获到的activeRef已经被标记为处于拖拽状态，根据它的值便可以轻松判断当前的状态，并决定要不要记录下在列表中的初始位置；而此时activeItem作为一个state还没有被更新为最新的状态。总之，<strong>在父组件（也就是列表中）所有的eventhandler中都使用activeRef判断，activeItem作为状态仅仅用于更新高亮状态。</strong></p>
<h3 id="autoscroll"><a href="#autoscroll" class="headerlink" title="autoscroll"></a>autoscroll</h3><p>整体结构说完了，接下来要考虑的就是拖拽到两端的情况了。React Native的scroll还是有点难用的，没办法控制滚动速度。而为了达到最初设想的：拖拽到两端时会自动滚动，且滚动速度和距离两端的位置有关，那就不得不用点trick。</p>
<p>trick的原理其实也比较好理解：</p>
<ol>
<li>如果当前在滚动中，不做处理。</li>
<li>如果当前拖拽的元素超过了某一阈值，且当前没有在滚动中，那么根据<strong>当前拖拽元素的位置</strong>计算<strong>方向</strong>以及<strong>滚动的目标位置</strong>，并触发滚动。</li>
<li>在onScroll事件中监听（注意节流），在当前滚动的距离与目标位置比较接近时，判断<strong>触发下一次滚动</strong></li>
<li>如果当前位置已经无法在滚动，停止滚动。</li>
</ol>
<p>除了上述方案，不断地setTimeout或者setInterval也可以完成目的，事实上最初的版本也确实这么做的，只不过看起来会忽快忽慢。</p>
<p>在实现的过程中，也使用了reanimated提供的useSharedValue来存储方向，并使用useDerivedValue在方向变化时及时地在不触发重新渲染的情况下进行滚动。</p>
<p>控制滚动的代码如下：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">scrollToTarget</span>(<span class="params">forceScroll = <span class="literal">false</span></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 未进行拖拽</span></span><br><span class="line">    <span class="keyword">if</span> (activeRef.current === -<span class="number">1</span>) &#123;</span><br><span class="line">        scrollingRef.current = <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 滚动中就不滚了 </span></span><br><span class="line">    <span class="keyword">if</span> (scrollingRef.current &amp;&amp; !forceScroll) &#123;</span><br><span class="line">        scrollingRef.current = <span class="literal">true</span>;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 方向是0, 也就是没有在滚动</span></span><br><span class="line">    <span class="keyword">if</span> (direction.value === <span class="number">0</span>) &#123;</span><br><span class="line">        scrollingRef.current = <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 下一次滚动到的位置</span></span><br><span class="line">    <span class="keyword">const</span> nextTarget =</span><br><span class="line">        <span class="built_in">Math</span>.sign(direction.value) *</span><br><span class="line">            <span class="built_in">Math</span>.max(<span class="built_in">Math</span>.abs(direction.value), <span class="number">0.3</span>) *</span><br><span class="line">            <span class="number">300</span> +</span><br><span class="line">        contentOffsetYRef.current;</span><br><span class="line">    <span class="comment">// 当前到极限了</span></span><br><span class="line">    <span class="keyword">if</span> (</span><br><span class="line">        (contentOffsetYRef.current &lt;= <span class="number">2</span> &amp;&amp;</span><br><span class="line">            nextTarget &lt; contentOffsetYRef.current) ||</span><br><span class="line">        (contentOffsetYRef.current &gt;=</span><br><span class="line">            listContentHeight - (layoutRef.current?.height ?? <span class="number">0</span>) - <span class="number">2</span> &amp;&amp;</span><br><span class="line">            nextTarget &gt; contentOffsetYRef.current)</span><br><span class="line">    ) &#123;</span><br><span class="line">        scrollingRef.current = <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    scrollingRef.current = <span class="literal">true</span>;</span><br><span class="line">    <span class="comment">// 超出区域</span></span><br><span class="line">    targetOffsetYRef.current = <span class="built_in">Math</span>.min(</span><br><span class="line">        <span class="built_in">Math</span>.max(<span class="number">0</span>, nextTarget),</span><br><span class="line">        listContentHeight - (layoutRef.current?.height ?? <span class="number">0</span>),</span><br><span class="line">    );</span><br><span class="line">    <span class="comment">// 开始滚动</span></span><br><span class="line">    listRef.current?.scrollToOffset(&#123;</span><br><span class="line">        <span class="attr">animated</span>: <span class="literal">true</span>,</span><br><span class="line">        <span class="attr">offset</span>: targetOffsetYRef.current,</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><br>列表中onScroll的事件也十分简单粗暴：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">onScroll=&#123;<span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    contentOffsetYRef.current = e.nativeEvent.contentOffset.y;</span><br><span class="line">    <span class="comment">// 与目标距离小于2像素就强制再滚一次</span></span><br><span class="line">    <span class="keyword">if</span> (</span><br><span class="line">        activeRef.current !== -<span class="number">1</span> &amp;&amp;</span><br><span class="line">        <span class="built_in">Math</span>.abs(</span><br><span class="line">            contentOffsetYRef.current -</span><br><span class="line">                targetOffsetYRef.current,</span><br><span class="line">        ) &lt; <span class="number">2</span></span><br><span class="line">    ) &#123;</span><br><span class="line">        scrollToTarget(<span class="literal">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="高亮元素"><a href="#高亮元素" class="headerlink" title="高亮元素"></a>高亮元素</h2><p>根据上边的一大通分析，在这里已经把高亮简化成了“浮在列表上，且拖拽中的兄弟元素不需要移动位置”。在这个前提下，我们考虑到的思路有两种：</p>
<ul>
<li>给list传入一个额外的extra字段，其中放上activeItem；当activeItem变化时逐个元素进行比较，并更新对应元素的样式</li>
<li>list完全不动，在列表上再浮一个长的一模一样的列表元素，直接更新它就好了</li>
</ul>
<p>显然是第二种思路更简单一些。并且由于list的元素有memo，在拖拽时甚至list中的元素都不会重新渲染：<br><img src="http://storage.upup.fun/musicfree/QQ%E5%9B%BE%E7%89%8720230110234021.png" alt="代码截图"></p>
<p>而对这个“假高亮”的控制，只需要通过setNativeProps在开始拖拽时更新它的top、opacity和zIndex，滑动时更新它的top，并在拖拽结束时更新zIndex为-1，opacity为0隐藏掉，看起来似乎就是完全跟手的了：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ...</span></span><br><span class="line">onTouchMove=&#123;<span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    fakeItemRef.current!.setNativeProps(&#123;</span><br><span class="line">        <span class="attr">top</span>: offsetRef.current,</span><br><span class="line">        <span class="attr">opacity</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="attr">zIndex</span>: <span class="number">100</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;&#125;</span><br><span class="line">onTouchEnd=&#123;<span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    fakeItemRef.current!.setNativeProps(&#123;</span><br><span class="line">        <span class="attr">top</span>: <span class="number">0</span>,</span><br><span class="line">        <span class="attr">opacity</span>: <span class="number">0</span>,</span><br><span class="line">        <span class="attr">zIndex</span>: -<span class="number">1</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;&#125;</span><br><span class="line">onTouchCancel=&#123;<span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    fakeItemRef.current!.setNativeProps(&#123;</span><br><span class="line">        <span class="attr">top</span>: <span class="number">0</span>,</span><br><span class="line">        <span class="attr">opacity</span>: <span class="number">0</span>,</span><br><span class="line">        <span class="attr">zIndex</span>: -<span class="number">1</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></p>
<h2 id="执行回调"><a href="#执行回调" class="headerlink" title="执行回调"></a>执行回调</h2><p>接下来就需要拖拽结束后的处理了，这里其实是比较轻松的一步。在一通操作之下，我们记录下了某个元素在屏幕内移动的距离和列表滚动的距离，又强行限制住了列表的高度，那拖拽后的位置就很容易计算出来了：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">onTouchEnd=&#123;<span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">        <span class="comment">// activeRef.current是初始下标，计算一下偏移即可</span></span><br><span class="line">        index =</span><br><span class="line">            activeRef.current +</span><br><span class="line">            <span class="built_in">Math</span>.round(</span><br><span class="line">                (e.nativeEvent.pageY -</span><br><span class="line">                    initDragPageY.current +</span><br><span class="line">                    initDragLocationY.current) /</span><br><span class="line">                    itemHeight,</span><br><span class="line">            );</span><br><span class="line">        <span class="comment">// 注意范围约束</span></span><br><span class="line">        index = <span class="built_in">Math</span>.min(data.length, <span class="built_in">Math</span>.max(index, <span class="number">0</span>));</span><br><span class="line">        <span class="comment">// 起始下标: activeRef.current  结束下标: index</span></span><br><span class="line">        <span class="keyword">if</span> (activeRef.current !== index) &#123;</span><br><span class="line">            <span class="comment">// 计算下排序后的数组</span></span><br><span class="line">            <span class="keyword">let</span> nData = _data</span><br><span class="line">                .slice(<span class="number">0</span>, activeRef.current)</span><br><span class="line">                .concat(_data.slice(activeRef.current + <span class="number">1</span>));</span><br><span class="line">            nData.splice(index, <span class="number">0</span>, activeItem <span class="keyword">as</span> T);</span><br><span class="line">            <span class="comment">// 执行回调</span></span><br><span class="line">            onSortEnd?.(nData);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;           </span><br></pre></td></tr></table></figure></p>
<p>到这里就算差不多了，最终的效果也如开头的视频那样，大概看起来还可以。不过细看还是有瑕疵，比如点击时的水波纹效果无法扩散到拖拽按钮的位置，这也可以通过优化布局来解决（设置列表项宽度为屏幕宽度，拖拽按钮的position设置为absolute并放在列表项上层，也就是并排改成折叠）。但总体问题不大。</p>
<h1 id="其他优化思路"><a href="#其他优化思路" class="headerlink" title="其他优化思路"></a>其他优化思路</h1><p>这些是我在做的过程中的一些其他的优化思路和想法，也简单记录一下吧。</p>
<h2 id="状态合并"><a href="#状态合并" class="headerlink" title="状态合并"></a>状态合并</h2><p>这里指的是把和一个对象相关的一一对应的状态合并到一个对象中，或者说如果某些状态之前有比较强的关联关系，那似乎可以合在一起。比如：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[list, setList] = useState&lt;<span class="built_in">any</span>[]&gt;([]);</span><br><span class="line">[listChecked, setListChecked] = useState&lt;<span class="built_in">boolean</span>[]&gt;([]);</span><br></pre></td></tr></table></figure><br>可以合并成：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[checkList, setCheckList] = useState&lt;<span class="built_in">Array</span>&lt;&#123;<span class="attr">listItem</span>: <span class="built_in">any</span>, <span class="attr">checked</span>: <span class="built_in">boolean</span>&#125;&gt;&gt;([]);</span><br></pre></td></tr></table></figure><br>因为如果分开，需要修改list和listChecked时某些情况下可能会使元素被渲染两次，并且用memo优化时也需要写两个判断条件。</p>
<h2 id="把renderItem返回的组件用memo进行缓存"><a href="#把renderItem返回的组件用memo进行缓存" class="headerlink" title="把renderItem返回的组件用memo进行缓存"></a>把renderItem返回的组件用memo进行缓存</h2><p>就以本文中的选中为例，所有的选中状态都存在一个数组中，当一个元素被选中时，这个数组也会整个更新（重新生成一个新的数组），从而引发列表重新渲染，每个renderItem都会被调用一遍，而显然其他的所有元素都是不需要重新渲染的。因此用memo做缓存就很有必要。<br>个人感觉，给renderItem的组件做memo似乎更重要一些，但官网只写了renderItem不要用匿名函数（尽管我总觉得这个好像没啥用，因为重新渲染的话不管用不用匿名函数都会重新生成一个函数对象，也可能是我理解不到位吧）。同时renderItem要尽可能的轻量（减少副作用，组件尽量的简单一些），这样重新渲染的压力也会小一些。</p>
<h2 id="useRef"><a href="#useRef" class="headerlink" title="useRef"></a>useRef</h2><p>某些用来做标志位的值存在ref中就够了，完全不需要使用state。如果用了state，引发重新渲染不说，依赖这个标志位的callback如果使用useCallback优化了，那好像也没啥用，反正标志位一变就会重新生成个函数对象。以及一个作为标志位的state，如果在useEffect里面用到，那它写进useEffect的依赖中可能没什么必要，不写的话又违反hooks的使用规范，就挺尴尬的。</p>
<h1 id="结尾"><a href="#结尾" class="headerlink" title="结尾"></a>结尾</h1><p>大概就是这么多，拖了很久才决定写这么一个小总结（要不然过一阵子就更想不起来了）。顺带再简单介绍下MusicFree，这是个基于React Native开发的开源音乐播放器，可以通过写一个简单的js脚本来扩展音源，简单的介绍可以看github。</p>
<p>本文中的所有代码也都在github上可以看到：<a target="_blank" rel="noopener" href="https://github.com/maotoumao/MusicFree/blob/master/src/components/base/SortableFlatList.tsx">可以戳这里</a>；这个项目尽管说有些地方写的还是不好，但是感觉还是比较适合初学者的，拿来练手也不错。</p>
<p>如果你喜欢我的内容，也可以关注下公众号【一只猫头猫】，平时工作之余的一些想法以及做的一些其他的有趣的事情也会分享在公众号。应该不太会为了维持关注发水文，尽量发一些有意义的东西。感兴趣就随缘关注下吧~~~ 过一段时间<em>说不准</em>会更新个刷题系列，可以一起鸭~</p>

    </div>

    
    
    
        <div class="reward-container">
  <div>嘻嘻</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="猫头猫 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="猫头猫 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/images/wechat_channel.jpg">
            <span class="icon">
              <i class="fab fa-weixin"></i>
            </span>

            <span class="label">WeChat</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/React-Native/" rel="tag"><i class="fa fa-tag"></i> React Native</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/10/04/%E5%86%99%E4%B8%80%E4%B8%AA%E5%85%A8%E7%BD%91%E6%9C%80%E5%85%A8%E7%9A%84%E9%9F%B3%E4%B9%90%E6%92%AD%E6%94%BE%E5%99%A8/" rel="prev" title="写一个全网最全的音乐播放器">
      <i class="fa fa-chevron-left"></i> 写一个全网最全的音乐播放器
    </a></div>
      <div class="post-nav-item">
    <a href="/2023/02/16/%E6%90%AD%E5%BB%BA%E8%87%AA%E5%B7%B1%E7%9A%84GPT%E6%9C%8D%E5%8A%A1/" rel="next" title="【完整的练手小项目】搭建自己的GPT服务">
      【完整的练手小项目】搭建自己的GPT服务 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
      <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=477844082&auto=1&height=66"></iframe>

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%9C%80%E6%B1%82%E5%88%86%E6%9E%90-amp-%E5%AE%9E%E7%8E%B0%E6%80%9D%E8%B7%AF"><span class="nav-number">2.</span> <span class="nav-text">需求分析&amp;实现思路</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%96%B9%E6%A1%881%EF%BC%9A%E5%81%9A%E4%B8%80%E4%B8%AA%E8%B0%83%E5%8C%85%E4%BE%A0"><span class="nav-number">2.1.</span> <span class="nav-text">方案1：做一个调包侠</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%96%B9%E6%A1%882%EF%BC%9A%E8%87%AA%E5%B7%B1%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.2.</span> <span class="nav-text">方案2：自己实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%80%9A%E7%94%A8%EF%BC%9F%E5%AE%9A%E5%88%B6%EF%BC%9F"><span class="nav-number">2.2.1.</span> <span class="nav-text">通用？定制？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%8E%E4%B9%88%E6%89%8D%E8%83%BD%E4%B8%8D%E5%8D%A1%EF%BC%9F"><span class="nav-number">2.2.2.</span> <span class="nav-text">怎么才能不卡？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8B%96%E6%8B%BD%E6%8E%92%E5%BA%8F%E6%80%8E%E4%B9%88%E5%AE%9E%E7%8E%B0%EF%BC%9F"><span class="nav-number">2.2.3.</span> <span class="nav-text">拖拽排序怎么实现？</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%86%8D%E6%9D%A5%E4%B8%80%E4%B8%AA%E9%97%AE%E9%A2%98"><span class="nav-number">2.2.3.1.</span> <span class="nav-text">再来一个问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%89%8D%E6%8F%90%E6%9D%A1%E4%BB%B6"><span class="nav-number">2.2.3.2.</span> <span class="nav-text">前提条件</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88"><span class="nav-number">3.</span> <span class="nav-text">技术方案</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%BB%9A%E5%8A%A8%E8%A1%8C%E4%B8%BA"><span class="nav-number">3.1.</span> <span class="nav-text">滚动行为</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B4%E4%BD%93%E7%BB%93%E6%9E%84"><span class="nav-number">3.1.1.</span> <span class="nav-text">整体结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#autoscroll"><span class="nav-number">3.1.2.</span> <span class="nav-text">autoscroll</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%AB%98%E4%BA%AE%E5%85%83%E7%B4%A0"><span class="nav-number">3.2.</span> <span class="nav-text">高亮元素</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%89%A7%E8%A1%8C%E5%9B%9E%E8%B0%83"><span class="nav-number">3.3.</span> <span class="nav-text">执行回调</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%85%B6%E4%BB%96%E4%BC%98%E5%8C%96%E6%80%9D%E8%B7%AF"><span class="nav-number">4.</span> <span class="nav-text">其他优化思路</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%8A%B6%E6%80%81%E5%90%88%E5%B9%B6"><span class="nav-number">4.1.</span> <span class="nav-text">状态合并</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8A%8ArenderItem%E8%BF%94%E5%9B%9E%E7%9A%84%E7%BB%84%E4%BB%B6%E7%94%A8memo%E8%BF%9B%E8%A1%8C%E7%BC%93%E5%AD%98"><span class="nav-number">4.2.</span> <span class="nav-text">把renderItem返回的组件用memo进行缓存</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useRef"><span class="nav-number">4.3.</span> <span class="nav-text">useRef</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%BB%93%E5%B0%BE"><span class="nav-number">5.</span> <span class="nav-text">结尾</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="猫头猫"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">猫头猫</p>
  <div class="site-description" itemprop="description">如果我是一只小猫咪，每天只要喵喵叫。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">31</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/maotoumao" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;maotoumao" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:lhx_xjtu@163.com" title="E-Mail → mailto:lhx_xjtu@163.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">猫头猫</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">91k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">1:22</span>
   | <a href="http://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备20005224号-2 </a>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

  

</body>
</html>
